<template>
  <el-dialog :title="title" :visible="showDialog" width="800px" @close="cancel">
    <el-form ref="form" :model="formData" :rules="rules">
      <el-form-item label="经纪" label-width="80px" prop="agent">
        <template>
          <el-select v-model="formData.agent" placeholder="请选择经纪人">
            <el-option
              v-for="item in agentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </template>
      </el-form-item>
      <el-form-item label="分类" label-width="80px" prop="category">
        <template>
          <el-select v-model="formData.category" placeholder="请选择分类">
            <el-option
              v-for="item in cateList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </template>
      </el-form-item>
      <el-form-item label="标题" label-width="80px" prop="title">
        <el-input v-model="formData.title" />
      </el-form-item>
      <el-form-item label="标签" label-width="80px" prop="tags">
        <el-tag
          v-for="tag in formData.tags"
          :key="tag"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)"
        >
          {{ tag }}
        </el-tag>
        <el-input
          v-if="inputVisible"
          ref="saveTagInput"
          v-model="inputValue"
          class="input-new-tag"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        />
        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
      </el-form-item>
      <el-form-item label="地址" label-width="80px" prop="address">
        <el-row type="flex">
          <el-cascader
            :options="addressList"
            placeholder="选择区域"
            :props="{value: 'name', label:'name', children: 'children'}"
            @change="handleChange"
          />
          <el-input v-model="formData.address" />
        </el-row>
      </el-form-item>
      <el-form-item label="价格" label-width="80px" prop="price">
        <el-input v-model="formData.price" />
      </el-form-item>
      <el-form-item label="描述" label-width="80px" prop="desc">
        <el-input v-model="formData.desc" type="textarea" rows="3" />
      </el-form-item>
      <el-form-item label="内容" label-width="80px" prop="content">
        <template>
          <!-- bidirectional data binding（双向数据绑定） -->
          <quill-editor
            v-model="formData.content"
            @blur="$refs.form.validateField('content')"
          />
        </template>
      </el-form-item>
      <el-form-item label="介绍图片" label-width="80px" prop="photos">
        <!-- 图片上传 -->
        <el-upload
          :file-list="fileList"
          action=""
          list-type="picture-card"
          :on-remove="handleRemove"
          :http-request="imageUpload"
        >
          <i class="el-icon-plus" />
        </el-upload>

        <el-input placeholder="强制设置图片跳过上传" />
      </el-form-item>
      <el-form-item>
        <el-form-item label="封面" label-width="80px" prop="image">
          <!-- 图片上传 -->
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :http-request="imgUpload"
          >
            <img v-if="formData.image" :src="formData.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
          <el-input placeholder="强制设置图片跳过上传" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="end">
            <el-button size="mini" type="primary" @click="submit">确定</el-button>
            <el-button size="mini" @click="cancel">取消</el-button>
          </el-row>
        </el-form-item>
      </el-form-item></el-form>
  </el-dialog>
</template>

<script>
import COS from 'cos-js-sdk-v5'
// SECRETID 和 SECRETKEY 请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKID64BD3oOmzynW4N4WzNsZEsbXRM1kR0Vn',
  SecretKey: 'AxeFmIgzxthU9veCaqyxkdiaEgz63Net'
})

import { addressList } from '@/api/address'
import { getAgentsList } from '@/api/agents'
import { getCateList } from '@/api/categories'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import { addProper, properDetails, updateProper } from '@/api/properties'
export default {
  components: { quillEditor },
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    },
    id: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      fileList: [], // 回显图片的列表
      addressList: [], // 省市区
      agentList: '', // 经纪人列表
      cateList: '', // 分类列表
      formData: {
        title: '', // 标题
        desc: '', // 描述
        image: '', // 图片
        agent: null, // 属于哪个经纪人的id
        content: '', // 内容
        address: '', // 地址
        price: '', // 价格
        photos: [], // 图片， url 组成数组
        tags: [], // 标签，字符串组成数组
        category: null // 属于哪个分类id值
      },
      rules: {
        title: [{ required: true, message: '该项不能为空', trigger: 'blur' }],
        desc: [{ required: true, message: '请输入描述', trigger: 'blur' }]
      },
      // formData.tags: [],
      inputVisible: false,
      inputValue: ''
    }
  },
  async created() {
    // 获取省市区
    this.getAddressList()
    // 获取经纪人列表
    const res = await getAgentsList()
    this.agentList = res.data
    // 获取分类列表
    const res1 = await getCateList()
    this.cateList = res1.data
  },
  methods: {
    // 自定义上传图片 -- 封面
    imgUpload(file) {
      cos.uploadFile({
        Bucket: 'hr-91-1319204182', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-nanjing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: Date.now().toString(), /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        Body: file.file /* 必须，上传文件对象，可以是input[type="file"]标签选择本地文件后得到的file对象 */
      }, (err, data) => {
        if (err) {
          console.log('上传失败', err)
        } else {
          console.log('上传成功', data)
          // this.$emit('input', )
          this.formData.image = 'https://' + data.Location
        }
      })
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png'].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isJPG && isLt2M
    },
    async submit() { // 确认添加
      // 表单校验
      await this.$refs.form.validate()
      if (this.id) {
        await updateProper(this.formData)
        this.$message.success('修改房产成功')
      } else {
        await addProper(this.formData)
        // 提示
        this.$message.success('添加房产成功')
      }
      // 退出弹窗
      this.cancel()
      // 刷新列表
      // this.allFn()
      this.$emit('updateEvent')
    },
    cancel() { // 关闭弹窗
      this.$emit('update:showDialog', false)
      this.$refs.form.resetFields()
      // 清空表单数据
      this.formData = {
        title: '', // 标题
        desc: '', // 描述
        image: '', // 图片
        agent: null, // 属于哪个经纪人的id
        content: '', // 内容
        address: '', // 地址
        price: '', // 价格
        photos: [], // 图片， url 组成数组
        tags: [], // 标签，字符串组成数组
        category: null // 属于哪个分类id值
      }
    },
    // 自定义上传图片 -- 介绍图片
    imageUpload(file) {
      cos.uploadFile({
        Bucket: 'hr-91-1319204182', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-nanjing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: Date.now().toString(), /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        Body: file.file /* 必须，上传文件对象，可以是input[type="file"]标签选择本地文件后得到的file对象 */
      }, (err, data) => {
        if (err) {
          console.log('上传失败', err)
        } else {
          console.log('上传成功', data)
          // this.$emit('input', )
          this.formData.photos.push('https://' + data.Location)
        }
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },

    // 标签选择器
    handleClose(tag) {
      this.formData.tags.splice(this.formData.tags.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.formData.tags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },

    // 获取省市区
    async getAddressList() {
      const res = await addressList()
      this.addressList = res.data.map(item => {
        return {
          id: item.id,
          name: item.province,
          children: item.city.map(el => {
            return {
              id: el.id,
              name: el.city,
              children: el.district.map(i => {
                return {
                  id: i.id,
                  name: i.district
                }
              })
            }
          })
        }
      })
      // console.log(this.addressList)
    },
    // 级联的方法
    handleChange(val) {
      const arr = []
      val.forEach(item => {
        arr.push(item)
      })
      this.formData.address = arr.join(',')
    },

    // 数据回显
    getProperDetails() {
      this.$nextTick(async() => {
        const res = await properDetails(this.id)
        this.formData = res.data
        this.fileList = this.formData.photos.map(item => {
          return {
            url: item
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  ::v-deep .ql-container {
    height: 150px;
  }
</style>

